package com.isoftstone.demo.filter;

import com.isoftstone.demo.pojo.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * @author: 于浩强
 **/
public class AuthFilter implements Filter {

    private static String[] USER_URL = new String[]{"/demo/login", "/demo/show"};
    private static String[] STATIC = new String[] {"/demo/assets", "/demo/data", "/demo/files", "/demo/images", "/demo/plugins", "/demo/resources"};
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String requestURI = request.getRequestURI();
        if (isUser(requestURI) || isStatic(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpSession session = request.getSession();

        User user = (User)session.getAttribute("user");
        if (Objects.isNull(user)) {
            ((HttpServletResponse)servletResponse).sendRedirect(USER_URL[0] + "?type=2");
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    private boolean isUser(String requestURI) {
        for (String s : USER_URL) {
            if (requestURI.equals(s))
                return true;
        }
        return false;
    }

    private boolean isStatic(String requestURI) {
        for (String s : STATIC) {
            if (requestURI.startsWith(s)) {
                return true;
            }
        }
        return false;
    }
}
